/**
 *  Copyright 2011 Pavlov Dm.
 *  Licensed under the MIT License
 */


package org.motiv.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * This sub-class starts with an initial size which is a closer match for cache usage.
 * @author Pavlov Dm
 */
public final class MemoryEfficientByteArrayOutputStream extends ByteArrayOutputStream {
    /**
     * Creates a new byte array output stream, with a buffer capacity of
     * the specified size, in bytes.
     * @param size the initial size.
     */
    public MemoryEfficientByteArrayOutputStream(int size) {
        super(size);
    }
    /**
     * Factory method
     * @param serializable any Object that implements Serializable
     * @param estimatedPayloadSize how many bytes is expected to be in the Serialized representation
     * @return a ByteArrayOutputStream with a Serialized object in it
     * @throws java.io.IOException if something goes wrong with the Serialization
     */
    public static MemoryEfficientByteArrayOutputStream serialize(Serializable serializable, int estimatedPayloadSize) throws IOException {
        MemoryEfficientByteArrayOutputStream outstr = new MemoryEfficientByteArrayOutputStream(estimatedPayloadSize);
        ObjectOutputStream objstr = new ObjectOutputStream(outstr);
        objstr.writeObject(serializable);
        objstr.close();
        return outstr;
    }
}
